package org.megion.js.web;

 import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.json.JSONException;
import org.json.JSONObject;
import org.megion.js.dao.MemberDao;
import org.megion.js.domain.Member;
import org.megion.js.json.tree.TreeJsonProcessor;
import org.megion.js.model.HtmlMenuNode;
import org.megion.js.service.HtmlMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value="/")
public class MemberController {
	
	private Logger logger = LoggerFactory.getLogger(MemberController.class);
	
    @Autowired
    private MemberDao memberDao;
    
    @Autowired
    private HtmlMenuService htmlMenuService;


    @RequestMapping(method=RequestMethod.GET)
    public String displaySortedMembers(Model model)
    {
        model.addAttribute("newMember", new Member());
        model.addAttribute("members", memberDao.findAllOrderedByName());
        return "index";
    }

    @RequestMapping(method=RequestMethod.POST)
    public String registerNewMember(@Valid @ModelAttribute("newMember") Member newMember, BindingResult result, Model model)
    {
        if (!result.hasErrors()) {
            memberDao.register(newMember);
            return "redirect:/";
        }
        else {
            model.addAttribute("members", memberDao.findAllOrderedByName());
            return "index";
        }
    }
    
    @RequestMapping(method = RequestMethod.GET)
	public String getManagePages(HttpServletRequest request, Model model) {
		try {
			TreeJsonProcessor<HtmlMenuNode> treeJsonProcessor = new TreeJsonProcessor<HtmlMenuNode>(
					htmlMenuService);
			JSONObject top = treeJsonProcessor.feedRootNodes();
			model.addAttribute("topNodeJSON", top.toString());
		} catch (JSONException e) {
			logger.error(e.getMessage(), e);
		}
		return "manage/pages";
	}

	@RequestMapping(value = "feedChildMenus", method = RequestMethod.GET)
	public void feedChildMenus(HttpServletRequest request,
			HttpServletResponse response, Model model) throws IOException {
		String resultJSON;
		try {
			String nodeKey = ServletRequestUtils.getStringParameter(request,
					"nodeKey");
			Long nodeId = HtmlMenuNode.nodeKeytoId(nodeKey);
			TreeJsonProcessor<HtmlMenuNode> treeJsonProcessor = new TreeJsonProcessor<HtmlMenuNode>(
					htmlMenuService);

			JSONObject json = treeJsonProcessor.feedChildNodes(nodeId);
			resultJSON = json.toString();
		} catch (ServletRequestBindingException e) {
			logger.error(e.getMessage(), e);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		} catch (JSONException e) {
			logger.error(e.getMessage(), e);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}

		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate, max-age=0");
		response.setDateHeader("Expires", (new Date()).getTime());
		response.setContentType("application/json");

		PrintWriter pw = response.getWriter();
		try {
			logger.info("resultJSON: " + resultJSON);
			pw.write(resultJSON);
		} finally {
			pw.close();
		}
	}

	@RequestMapping(value = "feedTreeScopeMenus", method = RequestMethod.GET)
	public void feedTreeScopeMenus(HttpServletRequest request,
			HttpServletResponse response, Model model) throws IOException {
		String resultJSON;
		try {
			String nodeKey = ServletRequestUtils.getStringParameter(request,
					"nodeKey");
			Long nodeId = HtmlMenuNode.nodeKeytoId(nodeKey);
			TreeJsonProcessor<HtmlMenuNode> treeJsonProcessor = new TreeJsonProcessor<HtmlMenuNode>(
					htmlMenuService);

			JSONObject json = treeJsonProcessor.feedTreeScopeNodes(nodeId);
			resultJSON = json.toString();
		} catch (ServletRequestBindingException e) {
			logger.error(e.getMessage(), e);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		} catch (JSONException e) {
			logger.error(e.getMessage(), e);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}

		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate, max-age=0");
		response.setDateHeader("Expires", (new Date()).getTime());
		response.setContentType("application/json");

		PrintWriter pw = response.getWriter();
		try {
			logger.info("resultJSON: " + resultJSON);
			pw.write(resultJSON);
		} finally {
			pw.close();
		}
	}
}
